package com.fm.common.net.baseCoroutine.exception

import android.view.View
import kotlinx.coroutines.Job

/**
 * @CreateData:     2020/12/22
 * @Author:         lyy
 * @Description:    在 Android View 中使用的 Job，能够在 View 的生命周期内自动 Disposable
 */
fun Job.autoDispose(view: View) = AutoDisposableJob(view, this)

class AutoDisposableJob(private val view: View, private val job: Job) : Job by job, View.OnAttachStateChangeListener {

    private fun isViewAttached() = view.isAttachedToWindow || view.windowToken != null

    init {
        if (isViewAttached()) {
            view.addOnAttachStateChangeListener(this)
        } else {
            cancel()
        }

        invokeOnCompletion {
            view.post {
                view.removeOnAttachStateChangeListener(this)
            }
        }
    }

    override fun onViewAttachedToWindow(v: View?) = Unit

    override fun onViewDetachedFromWindow(v: View?) {
        cancel()
        view.removeOnAttachStateChangeListener(this)
    }
}